package com.wxmit.framework.excel.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.PageReadListener;
import com.alibaba.excel.util.ListUtils;
import com.wxmit.framework.excel.domain.ExcelDemo;
import org.apache.commons.collections4.CollectionUtils;

import java.util.List;
import java.util.function.Consumer;

/**
 * DTOPageReadListener
 *
 * @author huangxiong
 * @version V1.0
 * @date 2023/1/6 11:27
 */
public class DemoPageReadListener extends PageReadListener<ExcelDemo> {

    public static int BATCH_COUNT = 10;
    private List<ExcelDemo> cachedDataList;
    private final Consumer<List<ExcelDemo>> consumer;

    public DemoPageReadListener(Consumer<List<ExcelDemo>> consumer) {
        super(consumer);
        cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        this.consumer = consumer;
    }

    public void invoke(ExcelDemo data, AnalysisContext context) {
        this.cachedDataList.add(data);
        if (this.cachedDataList.size() >= BATCH_COUNT) {
            this.consumer.accept(this.cachedDataList);
            this.cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }

    }

    public void doAfterAllAnalysed(AnalysisContext context) {
        if (CollectionUtils.isNotEmpty(this.cachedDataList)) {
            this.consumer.accept(this.cachedDataList);
        }

    }

    @Override
    public void onException(Exception exception, AnalysisContext context) throws Exception {
        //do nothing ...
        exception.printStackTrace();
    }
}
